package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"guliedu/model"
	"net/http"
	"strconv"
)

type teacherQuery struct {
	Name  string `json:"name"`
	Level int    `json:"level"`
}

func SelectAllTeacher(ctx *gin.Context) {
	teachers, _ := eduTeacherService.SelectAll()
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": teachers,
	})
	return
}

func SelectPageTeacher(ctx *gin.Context) {
	page := ctx.Param("page")
	pageSize := ctx.Param("pageSize")
	pageInt, _ := strconv.Atoi(page)
	pageSizeInt, _ := strconv.Atoi(pageSize)
	t := &teacherQuery{}
	ctx.ShouldBind(t)

	eduTeachers, _ := eduTeacherService.SelectPage(pageSizeInt, pageInt, t.Name, t.Level)
	count, _ := eduTeacherService.SelectAllCount()
	data := make(map[string]interface{})
	data["total"] = count
	data["rows"] = eduTeachers

	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": data,
	})
	return
}

func Delete(ctx *gin.Context) {
	id := ctx.Param("id")
	eduTeacherService.Delete(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func InsertOrSave(ctx *gin.Context) {
	t := &model.EduTeacher{}
	ctx.ShouldBind(&t)

	// id is null --> insert
	// id is not null --> save
	if t.ID != 0 {
		eduTeacherService.Update(t)
	} else {
		eduTeacherService.Insert(t)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
	})
	return
}

func SelectTeacher(ctx *gin.Context) {
	id := ctx.Param("id")
	t, _ := eduTeacherService.SelectByID(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": t,
	})
	return
}

func UploadProfile(ctx *gin.Context) {
	file, header, err := ctx.Request.FormFile("file")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(header.Filename)
	url, code := eduTeacherService.UploadProfile(file, header.Size)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"data": url,
	})
	return
}
